﻿//==================================================================
// Copyright (C) 2011 深圳市中旭企业管理股份有限公司
// 作 者：江怀玉
// Email:iSunStudio@hotmail.com
// 日 期：2011-10-14
// 描 述：扩展一些常用方法，含MD5加密,验证,JSON串处理
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
//==================================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using ZX.DBModule;
using System.Web.UI.WebControls;

namespace ZX.Common
{
   /// <summary>
    /// 扩展属性
    /// </summary>
    public static class ExtendMethods
    {
        // Hash an input string and return the hash as
        // a 32 character hexadecimal string.
        public static string GetMd5Hash(this string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        // Verify a hash against a string.
        public static bool VerifyMd5Hash(this string input, string hash)
        {
            // Hash the input.
            string hashOfInput = input.GetMd5Hash();

            // Create a StringComparer an comare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }

            return false;
        }


        /// <summary>
        /// 扩展Entity功能，可以直接转换成JSON数据格式
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string ToJSON(this BaseEntity entity)
        {
            return Globals.getJSON(entity);
        }


        public static string ToJSON(this IList<BaseEntity> list) 
        {
            //return Globals.ObjectToJSON(list);
            return Globals.getJSON<BaseEntity>(list);
        }

        public static string ToJSON(this object[] list)
        {
            return Globals.ObjectToJSON(list);
        }
    }
}

